package com.bbcare.nutritious.plat.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateTimeUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.JsonToEnetityUtil;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ExcelUtil.ExcelUtil.ExcelExportData;
import com.bbcare.comm.ExcelUtil.FileDownloadUtils;
import com.bbcare.nutritious.plat.entity.PtBloodsugarRecord;
import com.bbcare.nutritious.plat.entity.PtWeight;
import com.bbcare.nutritious.plat.service.IWeightService;

/**
 * 孕妇体重控制器
 */
@Controller
@RequestMapping("/webapi/service/weight")
public class WeightController {
	
    public static final Logger logger = Logger.getLogger(WeightController.class);
    
    @Autowired
    private IWeightService weightService;

    /**
     * 保存或修改体重信息
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/weightJoin")
    public ResultModel<Object> weightJoin(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in weightJoin----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtWeight weight = (PtWeight) JsonToEnetityUtil.jsonToObject(requestParam, PtWeight.class);
        //判空
        if(StringUtils.isEmpty(weight.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"患者ID不能为空");
        }
        if(StringUtils.isEmpty(weight.getWeightNumber())){
        	logger.debug("out Weight_Number----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"患者体重不能为空");
        }
        if(StringUtils.isEmpty(weight.getTestDate())){
        	logger.debug("out Weight_Number----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"日期不能为空");
        }
        
        Map<String,Object> rspMap = weightService.saveWeight(weight);
        logger.debug("out weightJoin----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 查询孕妇体重数据
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/listWeightForPage")
    public ResultModel<Object> listWeightForPage(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in listWeightForPage----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtWeight weight = (PtWeight) JsonToEnetityUtil.jsonToObject(requestParam, PtWeight.class);
        //判空
        if(StringUtils.isEmpty(weight.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"患者ID不能为空");
        }
        if(weight.getCurPage()<1){
        	logger.debug("分页页码小于1");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"分页页码不能小于1");
        }
        //日期查询条件判断
        if(!StringUtils.isEmpty(weight.getStartDate())){
        	if(StringUtils.isEmpty(weight.getEndDate())){
        		logger.debug("查询孕妇体重日期参数单个为空");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,单个日期参数无法查询");
        	}else if(!weight.getStartDate().equals(weight.getEndDate()) && DateTimeUtil.compareDate(weight.getStartDate(),weight.getEndDate(), DateTimeUtil.yyyy_MM_dd)>-1){
        		logger.debug("查询孕妇体重日期参数错误:开始日期大于结束日期");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,开始日期大于结束日期");
        	}
        }
        //计算分页参数
        weight.setStartNum((weight.getCurPage()-1)*weight.getPageSize());
        //查询体重列表
        Map<String,Object> rspMap = weightService.listWeightForPage(weight);
        //将查询条件返回
        //rspMap.put("param", weight);
        logger.debug("out listWeightForPage----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    
    /**
     * 通过id,userid,日期 条件查询孕妇体重数据
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/listWeightByCond")
    public ResultModel<Object> listWeightByCond(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in listWeightByCond----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtWeight weight = (PtWeight) JsonToEnetityUtil.jsonToObject(requestParam, PtWeight.class);
        //日期查询条件判断
        if(!StringUtils.isEmpty(weight.getStartDate())){
        	if(StringUtils.isEmpty(weight.getEndDate())){
        		logger.debug("查询孕妇体重日期参数单个为空");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,单个日期参数无法查询");
        	}else if(!weight.getStartDate().equals(weight.getEndDate()) && DateTimeUtil.compareDate(weight.getStartDate(),weight.getEndDate(), DateTimeUtil.yyyy_MM_dd)>-1){
        		logger.debug("查询孕妇体重日期参数错误:开始日期大于结束日期");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,开始日期大于结束日期");
        	}
        }
        //查询体重列表
        Map<String,Object> rspMap = weightService.listWeightByIdAndDate(weight);
        //将查询条件返回
        //rspMap.put("param", weight);
        logger.debug("out listWeightByCond----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 获取体重图表数据
     * 日期-体重数据分析
     * 可以根据日期参数进行调整
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/listWeightByIdAndDate")
    public ResultModel<Object> listWeightByIdAndDate(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in listWeightByIdAndDate----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtWeight weight = (PtWeight) JsonToEnetityUtil.jsonToObject(requestParam, PtWeight.class);
        //日期查询条件判断
        if(!StringUtils.isEmpty(weight.getStartDate())){
        	if(StringUtils.isEmpty(weight.getEndDate())){
        		logger.debug("查询孕妇体重日期参数单个为空");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,单个日期参数无法查询");
        	}else if(!weight.getStartDate().equals(weight.getEndDate()) && DateTimeUtil.compareDate(weight.getStartDate(),weight.getEndDate(), DateTimeUtil.yyyy_MM_dd)>-1){
        		logger.debug("查询孕妇体重日期参数错误:开始日期大于结束日期");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,开始日期大于结束日期");
        	}
        }
        //查询体重列表
        Map<String,Object> rspMap = weightService.getWeightChartData(weight);
        //将查询条件返回
        //rspMap.put("param", weight);
        logger.debug("out listWeightByIdAndDate----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    
    /**
     * 通过id删除孕妇体重数据
     * @param request
     * @param id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value="/delWeightById")
    public ResultModel<Object> delWeightById(HttpServletRequest request, String id) throws Exception {
        logger.info("in delWeightById");
        Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
        //日期查询条件判断
        if(StringUtils.isEmpty(id)){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,参数id不能为空");
        }
        rspMap = weightService.delWeightById(id);
        logger.debug("out delWeightById----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    
    
    
    /**
     * 导出孕妇体重数据
     * @param request
     * @param jsonStr--日期段,userid
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value="/exportWeightData")
    public ResultModel<Object> exportWeightData(HttpServletRequest request, PtWeight weight,HttpServletResponse response) throws Exception {
        logger.info("in exportWeightData");
        Map<String,Object> rspMap = Collections.synchronizedMap(new HashMap<String,Object>());
        //日期查询条件判断
        if(!StringUtils.isEmpty(weight.getStartDate())){
        	if(StringUtils.isEmpty(weight.getEndDate())){
        		logger.debug("导出孕妇体重数据日期参数单个为空");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,单个日期参数无法查询");
        	}else if(!weight.getStartDate().equals(weight.getEndDate()) && DateTimeUtil.compareDate(weight.getStartDate(),weight.getEndDate(), DateTimeUtil.yyyy_MM_dd)>-1){
        		logger.debug("导出孕妇体重数据日期参数错误:开始日期大于结束日期");
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,开始日期大于结束日期");
        	}
        }
        //查询要导出的体重数据
        List<PtWeight> list = weightService.exportWeightData(weight);
        String name ;
        String phone ;
        if(CollectionUtils.isEmpty(list)){
        	logger.debug("该时间段内无数据");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误,该时间段内无可导出数据");
        }else{
        	name = list.get(0).getUserName();
        	phone = list.get(0).getPhoneNo();
        	if(StringUtils.isEmpty(weight.getStartDate()) || StringUtils.isEmpty(weight.getEndDate())){
        		weight.setStartDate(list.get(list.size()-1).getTestDate());
        		weight.setEndDate(list.get(0).getTestDate());
        	}
        }
        //开始导出数据到Excel
        String fileName = name+"-体重数据";
        //定义一个map集合 由于存取excel表格需要展示的数据信息
		LinkedHashMap<String, List<?>> map = new LinkedHashMap<String, List<?>>();
		map.put(fileName, list);
		List<String[]> fieldNames = new ArrayList<String[]>();
		fieldNames.add(new String[] { "testDate","weightNumber","lastUpdate" });
		//打印的excel表格 列名
		Map<String, String[]> moreColumns = new LinkedHashMap<String, String[]>();
		moreColumns.put("序号", new String[]{"序号"});
		moreColumns.put("日期", new String[]{"日期"});
		moreColumns.put("体重(Kg)", new String[]{"体重(Kg)"});
		moreColumns.put("录入/修改时间", new String[]{"录入/修改时间"});
		
		ExcelExportData setInfo = new ExcelExportData();
		setInfo.setDataMap(map);
		setInfo.setFieldNames(fieldNames);
		setInfo.setTitles(new String[] {fileName});
		//excel表格头部加入查询数据的日期起始值,电话,可以拼接其他的
		setInfo.setExportExcelDate(weight.getStartDate()+"~"+weight.getEndDate()+"   联系电话:"+phone);//设置导出日期
		setInfo.setMoreColumns(moreColumns);
		  
		FileDownloadUtils.exportFile(request,response, setInfo, fileName);
        
        logger.debug("out exportWeightData----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 通过id或者userid+testDate查询
     * @return 单个对象
     */
    @ResponseBody
    @RequestMapping("/getWeight")
    public ResultModel<Object> getWeight(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in getgymnasticBarbellForUpdate----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtWeight weight = (PtWeight) JsonToEnetityUtil.jsonToObject(requestParam, PtWeight.class);
        //判空 id为空 并且userid或testDate为空
        if(StringUtils.isEmpty(weight.getId()) && (StringUtils.isEmpty(weight.getUserId()) || StringUtils.isEmpty(weight.getTestDate()))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参错误");
        }
        weight.setStartDate("");
        weight.setEndDate("");
        //查询体重列表
        Map<String,Object> rspMap = weightService.getWeight(weight);
        logger.debug("out getgymnasticBarbellForUpdate----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
}
